package com.jyxd.web.hiscz.service;

import com.jyxd.web.dao.user.UserDao;
import com.jyxd.web.data.dto.HttpResult;
import com.jyxd.web.data.user.User;
import com.jyxd.web.util.ComputerConfiguration;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

import static com.jyxd.web.hiscz.webservice.WebService.requestWebService;
import static com.jyxd.web.util.ExecuteUtil.errorIfEmpty;

/**
 * 单点登录service
 */
@Service
public class SSOService {

    private static Logger logger = LoggerFactory.getLogger(SSOService.class);

    @Autowired
    private UserDao userDao;
    @Autowired
    private ComputerConfiguration computerConfiguration;

    /**
     * 单点登录注册服务
     *
     * @param map
     * @return
     */
    public HttpResult loginInfoRegister(Map<String, Object> map) {
        try {
            errorIfEmpty(map, "参数不能为空");
            errorIfEmpty(map.get("userId"), "平台中统一用户的ID不能为空");
            errorIfEmpty(map.get("loginId"), "登录用户工号不能为空");
            User user = getUser(map);
            errorIfEmpty(user, "用户不存在");
            map = getResultMap("LoginInfoRegister", getLoginInfoRegisterXml(map, user.getUserName()));
            errorIfEmpty(map, "webService服务返回数据不存在");
            logger.info("webService 返回值为 >> " + map);
            logger.info(map.get("retcode").toString()+"=================");
            if (!StringUtils.equals((String) map.get("retcode"), "AA"))
                return new HttpResult(500, "单点登录服务注册失败，失败原因：" + map.get("msg"));
            user.setAppUserId((String) map.get("userId"));
            userDao.update(user);
            return new HttpResult(200, "单点登录服务注册成功");
        } catch (Exception e) {
            return new HttpResult(500, "接口请求错误：" + e.getMessage());
        }
    }

    private String getLoginInfoRegisterXml(Map<String, Object> map, String loginName) {
        errorIfEmpty(map, "参数不存在");
        String userId = (String) map.get("userId");
        String loginId = (String) map.get("loginId");
        return getRequestEndXml(
                getPassWordXml(
                        getLoginNameXml(getLoginIdXml(
                                getUserIdXml(
                                        getAppidXml(
                                                getRequestHeaderXml(), "zz"), userId), loginId), loginName), "")).toString();
    }

    /**
     * 单点登录安全验证
     *
     * @param map
     * @return
     */
    public HttpResult loginVerify(Map<String, Object> map, HttpServletRequest request) {
        try {
            errorVerdict(map);
           map = getResultMap("LoginVerify", getLoginVerifyXml(map, request));
          if (!StringUtils.equals((String) map.get("retcode"), "AA"))
               return new HttpResult(500, "单点登录安全验证失败，失败原因：" + map.get("msg"));
            return new HttpResult(200, "单点登录安全验证成功");
        } catch (Exception e) {
            return new HttpResult(500, "接口请求错误：" + e.getMessage());
        }
    }

    /**
     * 获取单点安全验证参数
     *
     * @param map
     * @param request
     * @return
     */
    private String getLoginVerifyXml(Map<String, Object> map, HttpServletRequest request) {
        errorIfEmpty(map, "参数不存在");
        String captcha = (String) map.get("captcha");
        String loginId = (String) map.get("loginId");
        return getRequestEndXml(
                getCaptchaXml(
                        getMacAddressXml(
                                getLoginIdXml(
                                        getApplicationIdXml(
                                                getRequestHeaderXml(), "zz"), loginId), computerConfiguration.getMac(request)), captcha)).toString();
    }

    /**
     * 单点登录系统退出通知
     *
     * @param map
     * @return
     */
    public HttpResult loginExit(Map<String, Object> map, HttpServletRequest request) {
        try {
            errorVerdict(map);
            errorIfEmpty(map.get("userId"), "平台中统一用户的ID不能为空");
            map = getResultMap("SystemColsed", getLoginExitXml(map, request));
            if (!StringUtils.equals((String) map.get("retcode"), "AA"))
                return new HttpResult(500, "退出系统失败，失败原因：" + map.get("msg"));
            return new HttpResult(200, "退出系统成功");
        } catch (Exception e) {
            return new HttpResult(500, "接口请求错误：" + e.getMessage());
        }
    }

    /**
     * 获取单点安全验证参数
     *
     * @param map
     * @param request
     * @return
     */
    private String getLoginExitXml(Map<String, Object> map, HttpServletRequest request) throws UnknownHostException {
        errorIfEmpty(map, "参数不存在");
        String captcha = (String) map.get("captcha");
        String loginId = (String) map.get("loginId");
        String userId = (String) map.get("userId");
        return getRequestEndXml(
                getCaptchaXml(
                        getIpXml(
                                getMacAddressXml(
                                        getLoginIdXml(
                                                getUserIdXml(
                                                        getApplicationIdXml(
                                                                getRequestHeaderXml(), "zz"),
                                                        userId),
                                                loginId),
                                        computerConfiguration.getMac(request)),
                                getIp(request)),
                        captcha)).toString();
    }

    /**
     * 获取本地ip
     *
     * @param request
     * @return
     * @throws UnknownHostException
     */
    private String getIp(HttpServletRequest request) throws UnknownHostException {
        String ip = computerConfiguration.getIp(request);
        String localHostip= InetAddress.getLocalHost().getHostAddress();
        if (StringUtils.equals(ip, localHostip))
            return localHostip;
        return null;
    }

    /**
     * 空值判断
     *
     * @param map
     */
    private void errorVerdict(Map<String, Object> map) {
        errorIfEmpty(map, "参数不能为空");
        errorIfEmpty(map.get("captcha"), "验证码不能为空");
        errorIfEmpty(map.get("loginId"), "平台中统一用户的ID不能为空");
    }

    /**
     * 获取用户
     *
     * @param map
     * @return
     */
    private User getUser(Map<String, Object> map) {
        map.put("workNumber", map.get("loginId"));
        return userDao.queryDataByWorkNumber(map);
    }

    /**
     * 获取webService请求返回值
     *
     * @param portName
     * @return
     */
    private Map<String, Object> getResultMap(String portName, String xml) {
        Map<String, Object> register = requestWebService(portName, xml);
        errorIfEmpty(register, "webService服务返回值错误");
        return register;
    }


    private StringBuffer getRequestHeaderXml() {
        StringBuffer requestParam = new StringBuffer();
        requestParam.append("<?xml version=\"1.0\" encoding=\"GB2312\" standalone=\"yes\"?>");
        requestParam.append("<data>");
        return requestParam;
    }

    private StringBuffer getAppidXml(StringBuffer requestParam, String appId) {
        requestParam.append("<appid>").append(appId).append("</appid>");
        return requestParam;
    }

    private StringBuffer getUserIdXml(StringBuffer requestParam, String userId) {
        requestParam.append("<userid>").append(userId).append("</userid>");
        return requestParam;
    }

    private StringBuffer getLoginIdXml(StringBuffer requestParam, String loginId) {
        requestParam.append("<loginid>").append(loginId).append("</loginid>");
        return requestParam;
    }

    private StringBuffer getLoginNameXml(StringBuffer requestParam, String loginName) {
        requestParam.append("<loginname>").append(loginName).append("</loginname>");
        return requestParam;
    }

    private StringBuffer getPassWordXml(StringBuffer requestParam, String passWord) {
        requestParam.append("<password>").append(passWord).append("</password>");
        return requestParam;
    }

    private StringBuffer getApplicationIdXml(StringBuffer requestParam, String applicationId) {
        requestParam.append("<applicationid>").append(applicationId).append("</applicationid>");
        return requestParam;
    }

    private StringBuffer getMacAddressXml(StringBuffer requestParam, String macAddress) {
        requestParam.append("<macaddress>").append(macAddress).append("</macaddress>");
        return requestParam;
    }

    private StringBuffer getIpXml(StringBuffer requestParam, String ip) {
        requestParam.append("<ip>").append(ip).append("</ip>");
        return requestParam;
    }

    private StringBuffer getCaptchaXml(StringBuffer requestParam, String captcha) {
        requestParam.append("<captcha>").append(captcha).append("</captcha>");
        return requestParam;
    }


    private StringBuffer getRequestEndXml(StringBuffer requestParam) {
        requestParam.append("</data>");
        return requestParam;
    }
}
